import deepmerge from 'deepmerge';
import defaults from 'axios/lib/defaults'
let defaultConfig = {
    /**
     * 默认超时2分钟: 60 * 1000 * 2
     */
    timeout: 12000,

    /**
     * 默认
     */
    headers: {
        "X-Requested-With": "XMLHttpRequest"
    },

    transitional: {
        silentJSONParsing: true,
        forcedJSONParsing: true,
        // 明确超时异常类型
        clarifyTimeoutError: true
    },

    /**
     * API Url前缀
     */
    baseURL: '',
    /**
     * request data 转换
     * this => config
     */
    transformRequest: [function (requestData, requestHeader) { // eslint-disable-line
        // this => config
        return requestData
    }].concat(defaults.transformRequest || []),

    /**
     * request data 转换
     * this => config
     */
    transformResponse: defaults.transformResponse.concat([function (responseData, requestHeader) { // eslint-disable-line
        // this => config
        return responseData
    }]),

    /**
     * 异常解析及规范 包括超时、取消异常、业务异常
     */
    resloveExcetionResponse(responseData, isHttpError) { // eslint-disable-line
        responseData = responseData || {}
        //错误描述
        let errMessage = null
        //错误代码
        let code = null
        if (responseData.code === 'ECONNABORTED') {
            errMessage = '请求已被中断!!'
            code = 'ECONNABORTED'
        } else if (responseData.message === 'Network Error') {
            errMessage = '网络连接异常!!'
            code = 'NETWORKERROR'
        } else if (responseData.code === 'ETIMEDOUT') {
            errMessage = '请求超时!!'
            code = 'ETIMEDOUT'
        }

        if ((!errMessage || !code) && isHttpError) {
            errMessage = '未知异常!!'
            code = 'UNKNOWN'
        }

        /**
         * 请在此处解析业务异常 
         */

        if (!errMessage || !code) {
            return null
        }
        return {
            errMessage,
            code
        }
    },

    /**
     * 当异常发生的时候,
     */
    whenExceptionFn: null,
}

let useConfig = null

export function getRequestConfig() {
    return useConfig || defaultConfig
}

export function setRequestConfig(megerConfig) {
    megerConfig = megerConfig || {}
    useConfig = {
        ...defaultConfig,
        ...megerConfig
    }
}